import { messages } from "share/common";
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import moment from 'moment'
import { Popover, Row, Col, message } from 'antd'
import Condition from 'components/condition'
import menuRoute from "routes/menuRoute";
import Ellipsis from "ant-design-pro/lib/Ellipsis";
import contractService from '../../../contract/contract.service';
import RelatedBill from '../components/related-bills'

const { If }  = Condition;

@connect(mapStateToProps)
class SlideExpenseReportDetailRelative extends Component {

  state = {
    contractHeaderOID: '',
    viewedList: [],
  };

  componentDidMount() {
    this.getContractOID();
  }

  getContractOID = () => {
    const { info } = this.context;
    info.contractHeaderId && contractService.getContractHeaderInfo(info.contractHeaderId).then(res => {
      this.setState({ contractHeaderOID: res.data.documentOid });
    })
  };

  onClickApplication = application => {
    const { contractHeaderOID, viewedList } = this.state;
    const { info } = this.context;
    const { menuTree } = this.props;
    const { expenseReportApplicationDTOS, contractHeaderId } = info;
    let totalNum = (expenseReportApplicationDTOS || []).length;
    contractHeaderId && totalNum++;
    if (totalNum > 1) {
      RelatedBill.open({
        visible: true,
        entityType: 1001,
        entityOID: application.applicationOID,
        info: Object.assign({}, info, { contractHeaderOID }),
        viewedList,
        afterClose: viewedList => this.setState({ viewedList })
      }, this)
    } else {
      if (menuTree.allAPIMenuItem["check-cost-application"]) {
        window.open(
          (window.ISIE9 ? "#" : "") + menuRoute.getRouteItem('cost-application-detail').url
            .replace(':formOID', application.applicationFormOID)
            .replace(':applicationOID', application.applicationOID) + `?from=expense&erApplicantOID=${info.applicantOID}`
        );
      } else if (menuTree.allAPIMenuItem["request"]) {
        window.open(
          (window.ISIE9 ? "#" : "") + menuRoute.getRouteItem('request-detail').url
            .replace(':formOID', application.applicationFormOID)
            .replace(':applicationOID', application.applicationOID) + `?from=expense&erApplicantOID=${info.applicantOID}`
        );
      } else {
        message.warning(messages('expense-14.key296')/*您没有申请单查看权限，请联系管理员*/);
      }
    }
  };

  handleContractClick = () => {
    const { contractHeaderOID, viewedList } = this.state;
    const { info } = this.context;
    const { expenseReportApplicationDTOS } = info;
    let totalNum = (expenseReportApplicationDTOS || []).length + 1;
    if (totalNum > 1) {
      RelatedBill.open({
        visible: true,
        entityType: 6001,
        entityOID: contractHeaderOID,
        info: Object.assign({}, info, { contractHeaderOID }),
        viewedList,
        afterClose: viewedList => this.setState({ viewedList })
      }, this)
    } else {
      window.open((window.ISIE9 ? '#' : '') + menuRoute.getRouteItem('contract-detail').url.replace(':entityOID', contractHeaderOID));
    }
  };

  static contextTypes = {
    info: PropTypes.object
  };

  renderRelativeItem = item => {
    const { info } = this.context;
    return (
      <Ellipsis lines={1}>
        {item.applicationBusinessCode}
        <If value={info.travelStartDate && info.travelEndDate}>
          ，{moment(item.travelStartDate).format('YYYY-MM-DD')}
          &nbsp;~&nbsp;
          {moment(item.travelEndDate).format('YYYY-MM-DD')}
        </If>
      </Ellipsis>
    )
  };

  render() {
    const { info } = this.context;
    const { viewedList, contractHeaderOID } = this.state;
    let expenseReportApplicationDTOS = info.expenseReportApplicationDTOS || [];
    return (
      <div className='slide-expense-report-detail-relative'>
        <If value={expenseReportApplicationDTOS.length > 0}>
          <Row>
            <Col span={6} className="slide-expense-report-detail-relative-title">
              {messages('expense-14.key297',{arg1: expenseReportApplicationDTOS.length})/*关联申请({arg1})：*/}
            </Col>
            <Col span={18}>
              {expenseReportApplicationDTOS.map(item => (
                <div
                  className={this.classNames([
                    'slide-expense-report-detail-relative-value', {
                    'viewed': viewedList.includes(item.applicationOID)
                  }])}
                  onClick={() => this.onClickApplication(item)}
                >
                  <Popover placement="topLeft" content={this.renderRelativeItem(item)}>
                    {this.renderRelativeItem(item)}
                  </Popover>
                </div>
              ))}
            </Col>
          </Row>
        </If>
        <If value={info.contractHeaderId}>
          <Row>
            <Col span={6} className="slide-expense-report-detail-relative-title">
              {messages('expense-14.key298',{arg1: 1})/*关联合同({arg1})：*/}
            </Col>
            <Col span={18}>
              <div
                className={this.classNames([
                  'slide-expense-report-detail-relative-value', {
                  'viewed': viewedList.includes(contractHeaderOID)
                }])}
                onClick={() => this.handleContractClick(info.contractHeaderId)}
              >
                <Popover placement="topLeft" content={info.contractNumber}>
                  {info.contractNumber}
                </Popover>
              </div>
            </Col>
          </Row>
        </If>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    menuTree: state.login.menuTree,
  }
}

export default SlideExpenseReportDetailRelative;
